﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeChatParking.Core.Payment.Alipay
{
    public class AlipayClient
    {

        public AlipayClient()
        {
        }


        
        /// <summary>
        /// 构建 即时到账请求
        /// </summary>
        /// <param name="req"></param>
        public string BuildDirectPayRequest(AlipayDirectPayRequest req)
        {

            req.Sign = AlipayHelper.GetSign(req.GetParameters(), AlipayConfig.Key);  
            string url= AlipayConfig.GateWayUrl + "_input_charset=" +AlipayConfig.Input_charset;
            string requestStr = PayUtil.CreateAutoSubmitForm(url, PayUtil.FilterPara(req.GetParameters()),"Post","支付宝支付", Encoding.UTF8);

            //SWShop.Model.Order_pay_log log = new Model.Order_pay_log();
            //log.order_sn = "支付宝支付";
            //log.note ="提交的表单：" + requestStr;
            //PayUtil.WriteOrderPayLog(log);

            return requestStr;

        }


        /// <summary>
        /// 验证消息是否是支付宝发出的合法消息
        /// </summary>
        /// <param name="req"></param>
        public bool VerifyAlipayMsg(Dictionary<string,string> parameters)
        {
            //获取返回时的签名验证结果
            bool isSign = AlipayHelper.CheckSign(parameters, AlipayConfig.Key,parameters["sign"]);


            ////获取是否是支付宝服务器发来的请求的验证结果
            //string notify_id = parameters["notify_id"];
            //string responseTxt = "true";
            //if (notify_id != null && notify_id != "") 
            //{
            //    string veryfyUrl = AlipayConfig.HttpVerifyUrl + "partner=" + AlipayConfig.Partner + "&notify_id=" + notify_id;
            //    //返回 URL 只有一分钟的有效期，超过一分钟该链接地址会失效，验证则会失败。
            //    webUtils.Timeout = 1200000;
            //    responseTxt = webUtils.DoGet(veryfyUrl, "UTF-8");
            //}

            ////判断responsetTxt是否为true，isSign是否为true
            ////responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
            ////isSign不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
            //if (responseTxt == "true" && isSign)//验证成功
            //{
            //    return true;
            //}
            //else//验证失败
            //{
            //    return false;
            //}

            //由于支付宝验证链接地址只有一分钟有效时期，容易失效，故只判断sign值作为验签结果
            if (isSign)//验证成功
            {
                return true;
            }
            else//验证失败
            {
                return false;
            }

        }


    }
}
